package com.anysoft.user.bankcard;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.anysoft.HostConstant;
import com.anysoft.MentorConst;
import com.anysoft.R;
import com.anysoft.adapter.BindBankCardAdapter;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.GetBankCardListBean;
import com.anysoft.utils.ActivityUtils;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.DepthPageTransformer;
import com.anysoft.utils.HttpUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 绑定银行卡列表页面
 */
public class BankCardManagerActivity extends BaseActivity implements View.OnClickListener {

    private final static int ADD_BANK_CARD = 107;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.rightButton)
    Button rightButton;
    @BindView(R.id.leftButton)
    Button leftButton;
    @BindView(R.id.tv_day_amount_val)
    TextView tv_day_amount_val;
    @BindView(R.id.tv_month_amount_val)
    TextView tv_month_amount_val;
    @BindView(R.id.tv_add_bank_card)
    TextView tv_add_bank_card;

    @BindView(R.id.viewPager)
    ViewPager viewPager;

    @BindView(R.id.lv_ban_card)
    ListView lv_ban_card;
    @BindView(R.id.rl_bank_car_info_layout)
    RelativeLayout rl_bank_car_info_layout;
    //    @BindView(R.id.image_not_bank_card)
//    ImageView image_not_bank_card;
    @BindView(R.id.ll_not_bank_card)
    LinearLayout ll_not_bank_card;

    @BindView(R.id.viewGroup)
    LinearLayout mViewPoints;

    ArrayList<Fragment> fragmentList;
//      FragmentManager fragmentManager;
    /**
     * 将小圆点的图片用数组表示
     */
    private ImageView[] imageViews;
    private ImageView imageView;


    private GetBankCardListBean bean;
    private BindBankCardAdapter adapter;
    private String currLoginFundCustomerNo = "";
    private TextView tv_bank_card_tip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bank_card_manager);
        ButterKnife.bind(this);
        title.setText("银行卡管理");
        rightButton.setBackgroundResource(R.drawable.ic_add_bank_card);
        FrameLayout.LayoutParams paramsRightButton = (FrameLayout.LayoutParams) rightButton.getLayoutParams();
        paramsRightButton.width = 60;
        paramsRightButton.height = 60;
        rightButton.setLayoutParams(paramsRightButton);
        showNotBankCardInfo(true);
        initListViewFoolter();
        currLoginFundCustomerNo = getFundCustomerNo();
        getBindBankCardList();


//        viewPager.setAdapter(new MyFrageStatePagerAdapter(getSupportFragmentManager()));
//        viewPager.setPageMargin(40);
//        viewPager.
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initListViewFoolter() {
        View footerView = View.inflate(this, R.layout.item_bank_card_footer, null);
        tv_bank_card_tip = (TextView) footerView.findViewById(R.id.tv_bank_card_tip);
        tv_bank_card_tip.setOnClickListener(this);
        lv_ban_card.addFooterView(footerView);
    }

    private void showNotBankCardInfo(boolean flag) {
        if (flag) {
            lv_ban_card.setVisibility(View.GONE);
//            rl_bank_car_info_layout.setVisibility(View.GONE);
            ll_not_bank_card.setVisibility(View.VISIBLE);
        } else {
            lv_ban_card.setVisibility(View.VISIBLE);
//            rl_bank_car_info_layout.setVisibility(View.VISIBLE);
            ll_not_bank_card.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.leftButton, R.id.rightButton, R.id.tv_add_bank_card})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_bank_card_tip://温馨提示
                selectWarmPromptByType("21");
                break;
            case R.id.leftButton:
                finish();
                break;
            case R.id.rightButton:
//                finish();
//                break;
//            case R.id.tv_add_bank_card:
                if (mentorApplication.needLogin()) {
                    ActivityUtils.gotoLogin(this, this.hasUser(), false, this.findUserId());
                    return;
                }
                Intent intent = new Intent(this, AddBankCardActivity.class);
                startActivityForResult(intent, ADD_BANK_CARD);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ADD_BANK_CARD://
                    getBindBankCardList();
                    break;
            }
        }
    }

    class MyFragmentPagerAdapter extends FragmentPagerAdapter {
        private ArrayList<Fragment> listFragments;

        public MyFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> al) {
            super(fm);
            listFragments = al;
        }

        public MyFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return listFragments.get(position);
        }

        @Override
        public int getCount() {
            return listFragments.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }
    }

    private class NavigationPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int position) {
            for (int i = 0; i < imageViews.length; i++) {
                imageViews[position]
                        .setBackgroundResource(R.drawable.indicator_normal_pressed);
                // 不是当前选中的page，其小圆点设置为未选中的状态
                if (position != i) {
                    imageViews[i]
                            .setBackgroundResource(R.drawable.indicator_normal);
                }
            }
//            showToast("请求卡号为："+bean.getData().get(position).getBankAccountNo()+"银行卡的限额信息");
        }

    }

    /**
     * 获取用户名下绑定的所有银行卡信息
     */
    private void getBindBankCardList() {

        if (mentorApplication.needLogin()) {
            ActivityUtils.gotoLogin(this, this.hasUser(), false, this.findUserId());
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("token", mentorApplication.userBean.getToken());//replace 此值需要从用户对象身上获取
        params.put("fundCustomerNo", mentorApplication.userBean.getFundCustomerNo());//
        Logger.t("-----QUERY_CUSTOMER_BANK-----").d(HttpUtils.createRequestUrl(this, HostConstant.QUERY_CUSTOMER_BANK, params));
        OkGo.<String>post(HostConstant.QUERY_CUSTOMER_BANK)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showNotBankCardInfo(true);
                        showToast(MentorConst.INTERNET_ERROR);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析服务端返回的数据
     *
     * @param json
     */
    private void parseJson(String json) {
//        json = "{\"respCode\": \"0000\",\"respMsg\": \"返回成功\",\"respTime\": \"2017-02-15 10:32:31\",\"data\": []}";
//
//        json = "{\"respCode\": \"0000\",\"respMsg\": \"返回成功\",\"respTime\": \"2017-02-15 10:32:31\",\"data\": [{\"capitalName\": \"通联支付\",\"capitalMode\": \"M\",\"bankName\": \"通联支付_中国农业银行\",\"tradeAccountNo\": \"1234567\",\"bankAccountName\": \"张一依\",\"bankCode\": \"003\",\"bankBranch\": \"中国农业银行股份有限公司邯郸复兴支行\"},{\"capitalName\": \"通联支付\",\"capitalMode\": \"M\",\"bankName\": \"中国工商银行\",\"tradeAccountNo\": \"436\",\"bankAccountName\": \"柳宗元\",\"bankCode\": \"020\",\"bankBranch\": \"兴业银行股份有限公司泰安肥城支行\"},{\"capitalName\": \"工行网银\",\"capitalMode\": \"4\",\"bankName\": \"中国工商银行\",\"tradeAccountNo\": \"40006837\",\"bankAccountName\": \"新手一\",\"bankCode\": \"002\",\"bankBranch\": \"中国工商银行\"}]}";
        try {
            bean = new Gson().fromJson(json, GetBankCardListBean.class);
        } catch (Exception exception) {
            showToast("数据解析异常，请联系管理员");
            return;
        }

        if (!CommonUtil.checkState(mActivity, bean, json)) {
            return;
        }
//        ResultBean resultBean = checkStateBean(bean, json);
//        if (!resultBean.isSuccess()) {
//            showToast(resultBean.getTip());
//            return;
//        }

        if (bean == null || bean.getData() == null || bean.getData().size() <= 0) {
            showNotBankCardInfo(true);
            return;
        }
        showNotBankCardInfo(false);
//        bindData();
        adapter = new BindBankCardAdapter(this, bean.getData());
        lv_ban_card.setAdapter(adapter);
    }

    /**
     * 绑定银行卡数据信息
     */
    private void bindData() {
        fragmentList = new ArrayList<>();
        for (int i = 0; i < bean.getData().size(); i++) {
            fragmentList.add(BankCardFragment.newInstance(i, bean.getData().get(i)));
        }
//        fragmentList.add(BankCardFragment.newInstance(1,null));
//        fragmentList.add(BankCardFragment.newInstance(2,null));
//        fragmentList.add(BankCardFragment.newInstance(3,null));
//        fragmentList.add(BankCardFragment.newInstance(4,null));

        viewPager.setOffscreenPageLimit(fragmentList.size());//卡片数量
        viewPager.setPageMargin(20);//两个卡片之间的距离，单位dp
        viewPager.setOffscreenPageLimit(2);
        viewPager.setCurrentItem(0);// 设置起始位置
        viewPager.setPageTransformer(true, new DepthPageTransformer());
        if (viewPager != null) {
            viewPager.removeAllViews();
        }
        // 创建imageviews数组，大小是要显示的图片的数量
        imageViews = new ImageView[fragmentList.size()];

        // 添加小圆点的图片
        for (int i = 0; i < fragmentList.size(); i++) {
            imageView = new ImageView(this);
            // 设置小圆点imageview的参数
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    10, 10);
            layoutParams.setMargins(5, 0, 5, 0);
            imageView.setLayoutParams(layoutParams);// 创建一个宽高均为20 的布局
            // 将小圆点layout添加到数组中
            imageViews[i] = imageView;
            // 默认选中的是第一张图片，此时第一个小圆点是选中状态，其他不是
            if (i == 0) {
                imageViews[i]
                        .setBackgroundResource(R.drawable.indicator_normal_pressed);
            } else {
                imageViews[i]
                        .setBackgroundResource(R.drawable.indicator_normal);
            }

            // 将imageviews添加到小圆点视图组
            mViewPoints.addView(imageViews[i]);
        }


        MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);

        viewPager.setAdapter(myFragmentPagerAdapter);
        viewPager.setOnPageChangeListener(new NavigationPageChangeListener());
    }

    //手动设置ViewPager要显示的视图
    private void changeView(int desTab) {
        viewPager.setCurrentItem(desTab, true);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!mentorApplication.needLogin() && !getFundCustomerNo().equals(currLoginFundCustomerNo)) {
            currLoginFundCustomerNo = getFundCustomerNo();
            getBindBankCardList();
        }
        if (mentorApplication.needLogin()) {
            currLoginFundCustomerNo = "";
        }
    }
}
